package no21.thread;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 用java模拟4X100接力赛 当结束后 报成绩，应用CyclicBarrier
 * 
 * @author gao
 */
class Player implements Runnable {
	private String name;
	private CyclicBarrier barrier;

	public Player(String name, CyclicBarrier barrier) {
		super();
		this.name = name;
		this.barrier = barrier;
	}

	@Override
	public void run() {
		try {
			System.out.println(name + " 用时：XX ms" + ",交接棒");
			barrier.await();			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

public class CyclicBarrierDemo {
	public static void main(String[] args) throws InterruptedException {
		final StringBuilder sb = new StringBuilder();
		final Player[] players = new Player[4];
		ExecutorService exec = Executors.newCachedThreadPool();
		CyclicBarrier barrier = new CyclicBarrier(4, new Runnable() {
			@Override
			public void run() {
				System.out.println("第 "+sb.toString()+"轮结束，总用时  xxxxx ms：");				
			}
		});
		for (int i = 0; i < 4; i++) {
			players[i] = new Player("队员" + (i + 1), barrier);
		}
		for(int i = 0; i < 2; i++){
			sb.append(i+1);
			for (int j = 0; j < players.length; j++) {
				exec.execute(players[j]);
			}			
			TimeUnit.SECONDS.sleep(1);
		}
	}
}
